<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
</head>

<body>
</body>
<script>
    let count = 0;
    function myPromise(fn) {
        this.cbs = []

        this.id = count;
        count += 1;

        const resolve = (value) => {
            setTimeout(() => {
                this.cbs.forEach((cb => cb(value)))
            })
        }

        fn(resolve)
    }

    myPromise.prototype.then = function (onResolved) {
        return new myPromise((resolve) => {
            this.cbs.push((value) => {
                const res = onResolved(value);
                if (res instanceof myPromise) {
                    res.then(resolve)
                }
                else {
                    resolve(res)
                }
            })
            console.log("id", this.id, this.cbs)
        })
    }


    new myPromise((resolve) => {
        setTimeout(() => {
            resolve(1);
        }, 500);
    }).then((res) => {
        console.log(res)
        // return new myPromise((resolve) => {
        //     setTimeout(() => {
        //         resolve(2);
        //     }, 500);
        // });
        return 1
    }).then(console.log);

</script>

</html>